# 投资组合模型
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

# 从app中导入db实例以避免循环依赖
from app import db

class Portfolio(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    cash = db.Column(db.Float, default=0.0)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    stocks = db.relationship('PortfolioStock', backref='portfolio', lazy=True)
    
    @property
    def total_value(self):
        """计算投资组合总价值"""
        stock_value = sum(stock.quantity * stock.current_price for stock in self.stocks)
        return self.cash + stock_value
        
    def __repr__(self):
        return f'<Portfolio user_id={self.user_id}, cash={self.cash}>'

class PortfolioStock(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    portfolio_id = db.Column(db.Integer, db.ForeignKey('portfolio.id'), nullable=False)
    stock_id = db.Column(db.Integer, db.ForeignKey('stock.id'), nullable=False)
    quantity = db.Column(db.Integer, default=0)
    average_price = db.Column(db.Float, default=0.0)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    @property
    def current_price(self):
        """获取当前股价（实际应用中应从API获取）"""
        # 模拟数据，实际应用中应从股票API获取
        return 100.0  # 示例价格
        
    @property
    def market_value(self):
        """计算市值"""
        return self.quantity * self.current_price
        
    @property
    def profit_loss(self):
        """计算盈亏"""
        return (self.current_price - self.average_price) * self.quantity
        
    def __repr__(self):
        return f'<PortfolioStock portfolio_id={self.portfolio_id}, stock_id={self.stock_id}, quantity={self.quantity}>'